package cn.lili.controller.task;

import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.json.JSONUtil;
import cn.lili.common.properties.ProfileProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * MQClient
 *
 * @author moxingjian
 * @version 1.0
 * @date 2023-12-25 10:15
 * <p>
 * 版本更新：
 * 更新版本号    更新人      更新时间      更新内容
 */
@Slf4j
@Component
public class MQMonitorTask {

    @Value("${email.devEmail}")
    private String devEmail;

    @Resource
    private RocketMQTemplate rocketMQTemplate;
    @Resource
    private MailAccount mailAccount;
    @Resource
    private RedisTemplate redisTemplate;

    @Scheduled(cron = "0/10 * * * * ?")
    public void scanNameServerBroker() {
        org.apache.rocketmq.remoting.RemotingClient remotingClient = rocketMQTemplate.getProducer()
                .getDefaultMQProducerImpl().getMqClientFactory().getMQClientAPIImpl().getRemotingClient();
        String clientIP = rocketMQTemplate.getProducer().getClientIP();
        log.info("clientIP:{}", clientIP);
        // 注册的 NameServer
        List<String> nameServerAddressList = remotingClient.getNameServerAddressList();
        // 当前活跃的 NameServer
        List<String> availableNameSrvList = remotingClient.getAvailableNameSrvList();
        log.info("nameServerAddressList:{}", JSONUtil.toJsonStr(nameServerAddressList));
        log.info("availableNameSrvList:{}", JSONUtil.toJsonStr(availableNameSrvList));
        // 只要 nameServerAddressList 和 availableNameSrvList 大小不一致，即可做邮件通知，具体阈值自己设置！！！
        if (availableNameSrvList.size() < nameServerAddressList.size()) {
            BoundValueOperations boundValueOperations = redisTemplate.boundValueOps("rocketmq:nameserver");
            Object obj = boundValueOperations.get();
            if (obj == null || Boolean.FALSE.equals(Boolean.valueOf(obj.toString()))) {
                String errorInfo = String.format("NameServer少于%s，请及时启动， 当前值为：%s",
                        nameServerAddressList.size(), JSONUtil.toJsonStr(availableNameSrvList));
                log.error(errorInfo);
                String subject = ProfileProperties.getActiveProfile() + "环境的NameServer告警";
                // 邮件通知
                MailUtil.send(mailAccount, devEmail, subject, "监控信息：\n" + errorInfo, false, null);
                boundValueOperations.set(Boolean.TRUE);
            }
        }
    }

}
